package blog132;
import java.sql.*;

public class ServBean {
    private PreparedStatement dbStatement;
    private String errorText = "";
    private Connection conn;

    public String getErrorText(){
        return(errorText);
    }

    public ServBean() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection
                  ("jdbc:mysql://localhost/my1?user=root&password=3553&useUnicode=yes&characterEncoding=UTF-8");
        }  catch (ClassNotFoundException e) {
            errorText="Не найден драйвер БД";
            System.err.println(errorText);
        }  catch (SQLException e) {
            errorText="Не получилось подключиться к БД";
            System.err.println(errorText);
	    }
    }

    public ResultSet getMessages() {
        try {
            dbStatement = conn.prepareStatement("SELECT ID, Text FROM posts");
            return (dbStatement.executeQuery());
        }  catch (SQLException e) {
            errorText="Запрос к БД не прошел";
            System.err.println(errorText);
            return null;
	    }  catch (NullPointerException e) {
            return null;
        }

    }

    public void addMessage(String message) {
        try {
            dbStatement = conn.prepareStatement("INSERT INTO posts (Text) VALUES (?)");
            dbStatement.setString(1, message);
            dbStatement.executeUpdate();
            errorText="";
        }  catch (SQLException e) {
            errorText="Запрос к БД не прошел";
            System.err.println(errorText);
        }  catch (NullPointerException e) {

        }
    }

    public void disconnect() {
        try {
            dbStatement.close();
            conn.close();
        } catch (SQLException e) {

        }
    }

}
